﻿using System;
using System.Linq;
using System.Web;
using Model_SSResourceManager;
using Presenter_SSResourceManager;

namespace WebView_SSResourceManager
{
    public partial class EditResource : System.Web.UI.Page, IViewEditResource
    {
        private PresenterEditResource _presenter;
        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new PresenterEditResource(this);

            if (!IsPostBack)
                try
                {
                    _presenter.FillFieldToEdit();
                }
                catch (Exception)
                {
                    Response.Redirect("~/");
                }
        }

        public Guid GetResourceId()
        {
            var query = HttpContext.Current.Request.Url.Query.Where(symbol => symbol != '?');
            return Guid.Parse(new string(query.ToArray()));
        }

        public void FillPageFields(Resource resource)
        {
            Session["TempId"] = resource.Id;
            txtB_EndTime.Text = resource.EndTime.ToString();
            txtB_StartTime.Text = resource.StartTime.ToString();
            txtB_UsingTime.Text = resource.TimeOfUsing.TotalMinutes.ToString();
            txtB_Name.Text = resource.Name;
            txtB_UserCount.Text = resource.UserCount.ToString();
            chB_AutoTime.Checked = resource.OnlyAutoTime;
            chB_Locked.Checked = resource.Locked;
        }

        public Resource GatherPageFieldsInformation()
        {
            return new Resource()
                       {
                           Id = (Guid)Session["TempId"],
                           EndTime = TimeSpan.Parse(txtB_EndTime.Text),
                           StartTime = TimeSpan.Parse(txtB_StartTime.Text),
                           TimeOfUsing = TimeSpan.FromMinutes(double.Parse(txtB_UsingTime.Text)),
                           Locked = chB_Locked.Checked,
                           Name = txtB_Name.Text,
                           OnlyAutoTime = chB_AutoTime.Checked,
                           UserCount = Int32.Parse(txtB_UserCount.Text)
                       };
            
        }

        protected void Submit_OnClick(object sender, EventArgs e)
        {
            _presenter.Update();
        }


    }
}